package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"peilian-api/app/global/log"
	"peilian-api/utils/format"
	"runtime"
)

func Recover() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if res := recover(); res != nil {
				const size = 64 << 10
				buf := make([]byte, size)
				buf = buf[:runtime.Stack(buf, false)]

				log.Logger.Error(
					"recover from panic, ",
					"panic: ", fmt.Sprint(res),
					//" trace: ", string(buf),
				)
				c.JSON(http.StatusBadRequest, &format.Res{
					Code: http.StatusBadRequest,
					Data: make([]interface{}, 0),
					Msg:  fmt.Sprint(res),
				})
			}
		}()

		c.Next()
	}
}
